<!-- src/components/WordImporter.vue -->
<template>
  <div>
    <div>我是 tiptapOffice页面</div>
    <button @click="importWord">导入 Word 文档</button>
    <editor-content :editor="editor" />
  </div>
</template>

<script>
import { Editor, EditorContent } from '@tiptap/vue-2'
import StarterKit from '@tiptap/starter-kit'
import Table from '@tiptap/extension-table'

export default {
  components: { EditorContent },
  data() {
    return {
      editor: null,
    }
  },
  mounted() {
    this.editor = new Editor({
      extensions: [StarterKit, Table],
      content: '<p>点击按钮导入 Word 内容</p>',
    })
  },
  methods: {
    async importWord() {
      try {
        // 初始化 Office 环境
        await this.initializeOffice()
        // 读取并转换 Word 内容
        const htmlContent = await this.getWordContent()
        // 更新编辑器
        this.editor.commands.setContent(htmlContent)
      } catch (error) {
        console.error('导入失败:', error)
        alert('导入失败，请检查控制台')
      }
    },
    initializeOffice() {
      return new Promise((resolve, reject) => {
        Office.onReady((info) => {
          if (info.host === Office.HostType.Word) {
            resolve()
          } else {
            reject(new Error('仅支持 Word 环境'))
          }
        })
      })
    },
    async getWordContent() {
      return new Promise((resolve, reject) => {
        Word.run(async (context) => {
          // 加载文档正文和段落
          const body = context.document.body
          body.load('paragraphs, tables')
          await context.sync()

          // 转换为 HTML
          let html = ''
          // 处理段落
          body.paragraphs.items.forEach((para) => {
            html += this.parseParagraph(para)
          })
          // 处理表格
          // body.tables.items.forEach((table) => {
          //   html += this.parseTable(table)
          // })

          resolve(html)
        }).catch(reject)
      })
    },
    parseParagraph(paragraph) {
      let content = paragraph.text
      // 处理粗体
      if (paragraph.font?.bold) content = `<strong>${content}</strong>`
      // 处理斜体
      if (paragraph.font?.italic) content = `<em>${content}</em>`
      // 处理列表
      if (paragraph.listItem) {
        return `<li>${content}</li>`
      }
      return `<p>${content}</p>`
    },
    parseTable(table) {
      let html = '<table>'
      table.rows.items.forEach((row) => {
        html += '<tr>'
        row.cells.items.forEach((cell) => {
          html += '<td>'
          cell.paragraphs.items.forEach((para) => {
            html += this.parseParagraph(para)
          })
          html += '</td>'
        })
        html += '</tr>'
      })
      html += '</table>'
      return html
    }
  },
  beforeDestroy() {
    this.editor.destroy()
  }
}
</script>